package com.lg.edu.filter;

import com.lg.edu.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Component
@Slf4j
public class CookieFilter implements Ordered, GlobalFilter {

    @Reference(timeout = 300000)
    private UserService userService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        // 注册和登录接口跳过cookie过滤器
        String requestPath = request.getPath().toString();
        log.info("获取到请求路径：{}", requestPath);
        if (requestPath.contains("/user/register/")
                || requestPath.contains("/user/login/")
                || requestPath.contains("/user/getValidCodeByEmail/")
                || requestPath.contains("/code/")) {
            return chain.filter(exchange);
        }

        MultiValueMap<String, HttpCookie> cookieMultiValueMap = request.getCookies();
        HttpCookie cookie = cookieMultiValueMap.getFirst("lgToken");

        if (Objects.nonNull(cookie) && isNotEmpty(cookie.getValue())) {

            String token = cookie.getValue();
            log.info(">>>>>>>>>> 调用下游user服务进行token验证");
            // 调用下游user服务进行token信息验证
            String info = userService.getEmailByToken(token);
            if (StringUtils.isNotEmpty(info)) {
                log.info(">>>>>>>>>> token验证通过，放行");
                // cookie验证通过，放行
                return chain.filter(exchange);
            }
            log.info(">>>>>>>>>> token验证失败！");
        }

        // String clientIp = request.getRemoteAddress().getHostString();

        // cookie验证失败，拒绝访问，返回
        response.setStatusCode(HttpStatus.UNAUTHORIZED); // 状态码
        log.info("=====> cookie验证失败，将被拒绝访问！");
        String data = "Cookie authentication fails, access is denied";
        DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
        return response.writeWith(Mono.just(wrap));

    }


    /**
     * 返回值表示当前过滤器的顺序(优先级)，数值越小，优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return -100;
    }

    private boolean isNotEmpty(String str) {
        return Objects.nonNull(str) && !str.isEmpty();
    }
}
